<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/19
 * Time: 13:41
 */

namespace App\CronTask;

use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\MysqliPool\Mysql;
class RecentlyMatchCron extends AbstractCronTask
{
    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        return '*/2 * * * *';
    }
    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        // 定时任务名称
        return 'RecentlyMatch';
    }
    static function run(\swoole_server $server, int $taskId, int $fromWorkerId, $flags = null)
    {

        $tables = ['siam_kogmatchs','siam_csgomatchs','siam_lolmatchs','siam_dotamatchs'];
        $path = [UrlEnums::KOG_RECENTLY_MATCHS_PATH,UrlEnums::CSGO_RECENTLY_MATCHS_PATH,UrlEnums::LOL_RECENTLY_MATCHS_PATH,UrlEnums::DOTA_MATCH_RECENTLY_PATH];
        $matchs = [];
        //近期赛事列表
        for ( $i=0;$i<count($path);$i++ ){
            $url = UrlEnums::FJURL.$path[$i]."?offset=0&limit=100&version=2";
            $client = new HttpClient($url);
            list($s1, $s2) = explode(' ', microtime());
            $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
            $option = [
                'path'      => $path[$i],
                'api_time'  => $microtime
            ];
            $header = Auth::getInstance()->header($option);
            $client->setHeaders($header,true,false);
            $response = $client->get();
            $content = $response->getBody();
            $data = json_decode($content,true);
            MysqlPool::invoke(function (MysqlObject $db)use($data,$matchs,$tables,$i){
                if( isset($data['code']) && $data['code'] == 200 && $data['data'] ){
                    $db = Mysql::defer('mysql');
                    foreach ( $data['data'] as $item ){
                        $item['battle_ids'] = json_encode($item['battle_ids']);
                        $matchs[] = $item;
                    }
                }
                foreach ($matchs as $v){
                    $res = $db->where('match_id',$v['match_id'])->getOne($tables[$i]);
                    if( isset($v['match_time']) && $v['match_time'] ){
                        $v['start_time'] = $v['match_time'];
                    }
                    if( isset($v['map_bp']) ){
                        $v['map_bp'] = json_encode($v['map_bp']);
                    }
                    if( !$res ){
                        $raw = $db->insert($tables[$i],$v);
                    }else{
                        $raw = $db->where('match_id',$v['match_id'])->update($tables[$i],$v);
                    }
                }
            });
        }
    }
}